import createElement from "./createElement";
import updateChildren from "./updateChildren";

/**
 * 对比两个相同的虚拟节点
 * oldVnode: object 老节点
 * newVnode: object 新节点
*/
export default function patchVnode (oldVnode, newVnode) {
    // 1.判断新节点有无children
    if (newVnode.children === undefined) {
        // 新节点是一个文本节点
        // 判断新老节点的文本是否一样
        if (oldVnode.text !== newVnode.text) {
            oldVnode.elm.innerHTML = newVnode.text;
        }
    } else {
        // 判断旧节点有无children
        if (oldVnode.children && oldVnode.children.length) {
            // diff算法核心
            updateChildren(newVnode.children, oldVnode.children);
        } else {
            // 旧节点无children,直接用新节点的children替换
            const children = newVnode.children;
            const dom = oldVnode.elm;
            // 清空旧节点的文本
            dom.innerHTML = "";
            for (let child of children) {
                dom.appendChild(createElement(child));
            }
        }
    }
}